package me.frank.security.dto;

import lombok.Getter;
import me.frank.security.entity.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.List;

/**
 * @Author Frank Wang
 * @Description:
 * @Date 2018/12/11 13:49
 */
@Getter
public class CustomUserDetails extends User implements UserDetails {

    private static final long serialVersionUID = 1702923242319850756L;

    private final boolean enabled;
    private final boolean accountNonExpired;
    private final boolean credentialsNonExpired;
    private final boolean accountNonLocked;
    private final List<GrantedAuthority> authorities;

    public CustomUserDetails(User user) {
        if (user != null
                && !StringUtils.isBlank(user.getUsername())
                && !StringUtils.isBlank(user.getPassword())) {
            setUsername(user.getUsername());
            setPassword(user.getPassword());
            this.enabled = true;
            this.accountNonExpired = true;
            this.credentialsNonExpired = true;
            this.accountNonLocked = !user.getLocked();
            this.authorities = AuthorityUtils.createAuthorityList("admin");
        } else {
            throw new IllegalArgumentException("Cannot pass null or empty values to constructor");
        }
    }
}
